#include <iostream>
#include <string>
#include <mysql/mysql.h>
#include <thread>
#include <chrono>

int main(int argc, char** argv)
{
    MYSQL mysql;
    mysql_library_init(0, nullptr, nullptr);
    mysql_init(&mysql);

    std::string host = "127.0.0.1";
    //std::string host = "192.168.0.203";
    std::string user = "mysql_test";
    std::string pass = "123456";
    std::string db   = "mysql";

    // 设定超时3s
    // MYSQL_OPT_CONNECT_TIMEOUT:链接超时时间
    // MYSQL_OPT_READ_TIMEOUT:读超时时间
    // MYSQL_OPT_RECONNECT:断开重连 
    int to =  3;
    
    int ret = mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, &to);
    if (ret != 0)
    {
        std::cout << "mysql options  fialed!" << mysql_error(&mysql) << std::endl;
    }
    
    int recon = 1;
    ret = mysql_options(&mysql, MYSQL_OPT_RECONNECT, &recon);
    if (ret != 0)
    {
        std::cout << "mysql options  fialed!" << mysql_error(&mysql) << std::endl;
    }

    //  默认阻塞
    if (nullptr== mysql_real_connect(&mysql, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 3306, nullptr, 0))
    {
        std::cout << "mysql connect  fialed!" << mysql_error(&mysql) << std::endl;
    }

    // 超时设定
    // MYSQL_OPT_CONNECT_TIMEOUT()

    for(int i = 0; i < 10000; i++)
    {
        int re = mysql_ping(&mysql);
        if(0 == re)
        {
            std::cout << "mysql ping success!" << std::endl; 
        } 
        else
        {
            std::cout << host << "mysql ping failed " << mysql_error(&mysql) << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    std::cout << "mysql client " << std::endl;

    mysql_close(&mysql);
    mysql_library_end();


    return 0;
}